import { AppDataSource } from '../config/database';
import { AuthorizationCode } from '../entity/AuthorizationCode';
import { MockThirdParty } from '../mock/MockThirdParty';
import { User } from '../entity/User';

export class ThirdPartyAuth {
  private mockService: MockThirdParty;

  constructor(private appId: string, private appSecret: string) {
    this.mockService = new MockThirdParty(appId, appSecret);
  }

  async getAuthorizationCode(userId: string): Promise<string> {
    const userRepo = AppDataSource.getRepository(User);
    const user = await userRepo.findOne({ where: { userId } });
    
    if (!user) throw new Error('User not found');
    return this.mockService.generateAuthorizationCode(userId);
  }

  async getAccessToken(authorizationCode: string, appId: string, appSecret: string): Promise<string> {
    const result = await this.mockService.exchangeToken(authorizationCode);
    return result.access_token;
  }

  async revokeToken(token: string, appId: string, appSecret: string): Promise<boolean> {
    return this.mockService.revokeToken(token);
  }

  async getDeviceList(accessToken: string): Promise<{ did: string; name: string; type: string }[]> {
    return this.mockService.getDeviceList(accessToken);
  }
}